package com.rules.admin.login;



import com.alibaba.fastjson.JSON;
import com.rules.admin.utils.CookieUtils;
import com.rules.admin.vo.RuleUser;
import com.rules.core.utils.RedisUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;

@Component
public class DistributeUserHolder implements UserHolder<RuleUser> {
   private String domain;
   private Integer expireTime = 14400;
   private String path = "/";
   @Autowired
   private RedisUtils redisUtils;

   public void holdUser(RuleUser ruleUser) {
      String ticket = RandomStringUtils.randomAlphabetic(18).toUpperCase();
      Cookie cookie = new Cookie("ticket", ticket);
      if (StringUtils.isNotEmpty(this.path)) {
         cookie.setPath(this.path);
      }

      if (StringUtils.isNotEmpty(this.domain)) {
         cookie.setDomain(this.domain);
      }

      cookie.setMaxAge(this.expireTime);
      CookieUtils.addCookie(cookie);
      this.redisUtils.set(ticket, JSON.toJSONString(ruleUser),this.expireTime);
      //this.redisUtils.expire(ticket.getBytes(), this.expireTime);
   }

   public RuleUser getUser() {
      Cookie cookie = CookieUtils.getCookie("ticket");
      if (cookie == null) {
         return RuleUser.ANONYMOUS_USER;
      } else {
         String ticket = cookie.getValue();
         String userJson = this.redisUtils.get(ticket);
         if (userJson == null) {
            return RuleUser.ANONYMOUS_USER;
         } else {
            RuleUser ruleUser = JSON.parseObject(userJson,RuleUser.class);
            if (ruleUser == null) {
               return RuleUser.ANONYMOUS_USER;
            } else {
               this.redisUtils.set(ticket, JSON.toJSONString(ruleUser),this.expireTime);
               //this.redisInterface.expire(ticket.getBytes(), this.expireTime);
               return ruleUser;
            }
         }
      }
   }

   public void destroy() {
      Cookie cookie = CookieUtils.getCookie("ticket");
      if (cookie != null) {
         String ticket = cookie.getValue();
         String userJson= this.redisUtils.get(ticket);
         if (userJson != null) {
            this.redisUtils.delete(ticket);
         }
      }

   }

   public void setDomain(String domain) {
      this.domain = domain;
   }

   public void setExpireTime(Integer expireTime) {
      this.expireTime = expireTime;
   }

}
